package com.tony.demo.ui.performance.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.widget.ImageView;

import com.puhui.lib.utils.BitmapUtils;
import com.puhui.lib.utils.DMLog;
import com.puhui.lib.utils.DensityUtil;
import com.tony.demo.R;

public class ImageLoaderUtils {
    private static ImageLoaderUtils instance = null;
    private String cachePath = Environment.getExternalStorageDirectory() + "/mvp_demo";
    private ImageCache imageCache;

    private ImageLoaderUtils() {
    }

    public static ImageLoaderUtils getInstance() {
        if (instance == null) {
            synchronized (ImageLoaderUtils.class) {
                if (instance == null) {
                    instance = new ImageLoaderUtils();
                }
            }
        }
        return instance;
    }

    public void loadImage(Context context, String url, ImageView imageView) {
        if (null == imageCache) {
            imageCache = ImageCache.getInstance(context);
        }

        Bitmap bitmap = imageCache.getFromMemoryCache(url);
        if (null == bitmap) {
            int width = DensityUtil.dip2px(context, 100);
            int height = DensityUtil.dip2px(context, 80);
            Bitmap reusable = imageCache.getReusableBitmap(width, height, 1);
            bitmap = imageCache.getFromDiskCache(url, reusable);
            if (null == bitmap) {
                bitmap = BitmapUtils.compressBitmap(context, R.mipmap.reba, width, height, reusable);
                if (null != bitmap) {
                    DMLog.e(this.getClass().getCanonicalName(), "图片大小: " + bitmap.getByteCount() / 1024f / 1024f);
                    DMLog.e(this.getClass().getCanonicalName(), "从网络加载了图片");
                    imageCache.putToMemoryCache(url, bitmap);
                    imageCache.putToDiskCache(url, bitmap);
                }
            } else {
                DMLog.e(this.getClass().getCanonicalName(), "从磁盘中加载了图片");
            }
        } else {
            DMLog.e(this.getClass().getCanonicalName(), "从内存中加载了图片" + url);
        }

        if (null != bitmap && null != imageView) {
            imageView.setImageBitmap(bitmap);
        }
    }

    public void loadImage(Context context, int resourceId, int width, int height) {
        loadImage(context, resourceId, width, height, true);
    }

    public void loadImage(Context context, int resourceId, int width, int height, boolean inMutable) {
//        ImageCache.getInstance(context, cachePath).getBitmapFromMemory()
    }

//    public class ImageLoaderBuilder {
//        private String cachePath;
//
//        public ImageLoaderBuilder setCachePath(String cachePath) {
//            this.cachePath = cachePath;
//            return this;
//        }
//
//        public void build() {
//            ImageCache.getInstance().init();
//        }
//    }
}
